package com.girlbook.controllers;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;


@Path("/ueditor")
public class UeditorController
{
	private static Log logger = LogFactory.getLog(UeditorController.class);
	
	/**
	 * 图片上传
	 * @param inv
	 * @param files
	 * @return
	 * @throws Exception
	 */
	@Get("/imageUp")
	public String imageUp(Invocation inv, MultipartFile[] files)
			throws Exception
	{
		String filePath = "jsp/upload";
		HttpServletRequest request = inv.getRequest();
		String realPath = request.getSession().getServletContext()
				.getRealPath("/")
				+ "\\ueditor\\" + filePath;
		// 判断路径是否存在，不存在则创建
		File dir = new File(realPath);
		if (!dir.isDirectory())
			dir.mkdir();
		if (ServletFileUpload.isMultipartContent(request))
		{
			DiskFileItemFactory dff = new DiskFileItemFactory();
			dff.setRepository(dir);
			dff.setSizeThreshold(1024000);
			ServletFileUpload sfu = new ServletFileUpload(dff);
			FileItemIterator fii = sfu.getItemIterator(request);
			String title = ""; // 图片标题
			String url = ""; // 图片地址
			String fileName = "";
			String originalName = "";
			String state = "SUCCESS";

			try
			{
				while (fii.hasNext())
				{
					FileItemStream fis = fii.next();

					if (!fis.isFormField() && fis.getName().length() > 0)
					{
						fileName = fis.getName();
						Pattern reg = Pattern.compile("[.]jpg|png|jpeg|gif$");
						Matcher matcher = reg.matcher(fileName);
						if (!matcher.find())
						{
							state = "文件类型不允许！";
							break;
						}
						url = realPath
								+ "/"
								+ new Date().getTime()
								+ fileName.substring(fileName.lastIndexOf("."),
										fileName.length());
						BufferedInputStream in = new BufferedInputStream(
								fis.openStream());// 获得文件输入流
						FileOutputStream a = new FileOutputStream(new File(url));
						BufferedOutputStream output = new BufferedOutputStream(
								a);
						Streams.copy(in, output, true);// 开始把文件写到你指定的上传文件夹
					}
					else
					{
						String fname = fis.getFieldName();
						if (fname.indexOf("fileName") != -1)
						{
							BufferedInputStream in = new BufferedInputStream(
									fis.openStream());
							byte c[] = new byte[10];
							int n = 0;
							while ((n = in.read(c)) != -1)
							{
								originalName = new String(c, 0, n);
								break;
							}
							in.close();

						}
						if (fname.indexOf("upfile") != -1)
						{
							BufferedInputStream in = new BufferedInputStream(
									fis.openStream());
							byte c[] = new byte[10];
							int n = 0;
							while ((n = in.read(c)) != -1)
							{
								title = new String(c, 0, n);
								break;
							}
							in.close();
						}
					}

				}
			}
			catch (Exception e)
			{
				logger.error("----Exception----", e);
			}
			title = title.replace("&", "&amp;").replace("'", "&qpos;")
					.replace("\"", "&quot;").replace("<", "&lt;")
					.replace(">", "&gt;");
			return "@'original':'" + originalName + "','url':'" + filePath
					+ "/"
					+ url.substring(url.lastIndexOf("/") + 1, url.length())
					+ "','title':'" + title + "','state':'" + state + "'}";
		}

		return "";
	}

	/**
	 * 文件上传
	 * @param inv
	 * @param files
	 * @return
	 * @throws Exception
	 */
	@Get("/fileUp")
	public String fileUp(Invocation inv, MultipartFile[] files)
			throws Exception
	{
		String filePath = "jsp/upload";
		HttpServletRequest request = inv.getRequest();
		String realPath = request.getSession().getServletContext()
				.getRealPath("/")
				+ "\\ueditor\\" + filePath;
		File dir = new File(realPath);
		if (!dir.isDirectory())
			dir.mkdir();

		if (ServletFileUpload.isMultipartContent(request))
		{
			DiskFileItemFactory dff = new DiskFileItemFactory();
			dff.setRepository(dir);
			dff.setSizeThreshold(1024000);
			ServletFileUpload sfu = new ServletFileUpload(dff);
			FileItemIterator fii = sfu.getItemIterator(request);
			String title = ""; // 图片标题
			String url = ""; // 图片地址
			String fileName = "";
			String state = "SUCCESS";
			String contentType = "";
			while (fii.hasNext())
			{
				FileItemStream fis = fii.next();
				try
				{
					if (!fis.isFormField() && fis.getName().length() > 0)
					{
						fileName = fis.getName();
						Pattern reg = Pattern
								.compile("[.]rar|doc|zip|pdf|txt|swf|wmv$");
						Matcher matcher = reg.matcher(fileName);
						if (!matcher.find())
						{
							state = "文件类型不允许！";
							break;
						}
						contentType = fileName.substring(
								fileName.lastIndexOf("."), fileName.length());

						url = realPath
								+ "/"
								+ new Date().getTime()
								+ fileName.substring(fileName.lastIndexOf("."),
										fileName.length());

						BufferedInputStream in = new BufferedInputStream(
								fis.openStream());// 获得文件输入流
						FileOutputStream a = new FileOutputStream(new File(url));
						BufferedOutputStream output = new BufferedOutputStream(
								a);
						Streams.copy(in, output, true);// 开始把文件写到你指定的上传文件夹
					}
					else
					{
						String fname = fis.getFieldName();

						if (fname.indexOf("pictitle") != -1)
						{
							BufferedInputStream in = new BufferedInputStream(
									fis.openStream());
							byte c[] = new byte[10];
							int n = 0;
							while ((n = in.read(c)) != -1)
							{
								title = new String(c, 0, n);
								break;
							}
						}
					}

				}
				catch (Exception e)
				{
					logger.error("----Exception----", e);
				}
			}
			return "@{'url':'" + filePath + "/"
					+ url.substring(url.lastIndexOf("/") + 1, url.length())
					+ "','fileType':'" + contentType + "','state':'" + state
					+ "'}";
		}

		return "";
	}

	/**
	 * 图片管理
	 * 
	 * @param inv
	 * @return
	 * @throws Exception
	 */
	@Get("/imageManager")
	public String imageManager(Invocation inv) throws Exception
	{
		HttpServletRequest request = inv.getRequest();
		String path = "jsp/upload";
		String imgStr = "";
		String realpath = request.getSession().getServletContext()
				.getRealPath("/")
				+ "\\ueditor\\" + path;
		String abpath = request.getSession().getServletContext()
				.getRealPath("/")
				+ "\\ueditor\\";
		List<File> files = getFiles(realpath, new ArrayList<File>());
		for (File file : files)
		{
			imgStr += file.getPath().replace(abpath, "") + "ue_separate_ue";
		}
		imgStr = imgStr.substring(0, imgStr.lastIndexOf("ue_separate_ue"));
		imgStr = imgStr.replace("\\", "/");
		return "@" + imgStr;
	}

	/**
	 * 获取文件列表
	 * 
	 * @param realpath
	 * @param files
	 * @return
	 */
	private List<File> getFiles(String realpath, List<File> files)
	{
		File realFile = new File(realpath);
		if (realFile.isDirectory())
		{
			File[] subfiles = realFile.listFiles();
			for (File file : subfiles)
			{
				if (file.isDirectory())
				{
					getFiles(file.getAbsolutePath(), files);
				}
				else
				{
					Pattern reg = Pattern.compile("[.]jpg|png|jpeg|gif$");
					Matcher matcher = reg.matcher(file.getName());
					if (matcher.find())
					{
						files.add(file);
					}
				}
			}
		}
		return files;
	}

	/**
	 * 网络图片
	 * 
	 * @param inv
	 * @return
	 * @throws Exception
	 */
	@Get("/remoteImage")
	public String remoteImage(Invocation inv) throws Exception
	{
		HttpServletRequest request = inv.getRequest();
		request.setCharacterEncoding("UTF-8");
		String url = request.getParameter("upfile");
		String filePath = "jsp/upload";
		String[] arr = url.split("ue_separate_ue");
		String[] outSrc = new String[arr.length];
		for (int i = 0; i < arr.length; i++)
		{
			// 保存文件路径
			String savePath = request.getSession().getServletContext()
					.getRealPath("/")
					+ "\\ueditor\\" + filePath;// 保存路径
			// 格式验证
			Pattern reg = Pattern.compile("[.]jpg|png|jpeg|gif$");
			Matcher matcher = reg.matcher(arr[i]);
			if (!matcher.find())
			{
				return "";
			}
			String saveName = System.currentTimeMillis()
					+ arr[i].substring(arr[i].lastIndexOf("."));
			// 大小验证
			URL urla = new URL(arr[i]);
			URLConnection conn = urla.openConnection();

			File savetoFile = new File(savePath + "/" + saveName);
			outSrc[i] = filePath + "/" + saveName;
			try
			{
				InputStream is = conn.getInputStream();
				OutputStream os = new FileOutputStream(savetoFile);
				int b;
				while ((b = is.read()) != -1)
				{
					os.write(b);
				}
				os.close();
				is.close();
				// 这里处理 inputStream
			}
			catch (Exception e)
			{
				logger.error("----Exception----", e);
			}
		}
		String outstr = "";
		for (int i = 0; i < outSrc.length; i++)
		{
			outstr += outSrc[i] + "ue_separate_ue";
		}
		outstr = outstr.substring(0, outstr.lastIndexOf("ue_separate_ue"));
		return "@{'url':'" + outstr + "','tip':'远程图片抓取成功！','srcUrl':'" + url
				+ "'}";
	}

	/**
	 * 网络图片
	 * 
	 * @param inv
	 * @return
	 * @throws Exception
	 */
	@Get("/getMovie")
	public String getMovie(Invocation inv) throws Exception
	{
		HttpServletRequest request = inv.getRequest();
		request.setCharacterEncoding("UTF-8");
		StringBuffer readOneLineBuff = new StringBuffer();
		String content = "";
		String searchkey = request.getParameter("searchKey");
		String videotype = request.getParameter("videoType");
		try
		{
			URL url = new URL("http://api.tudou.com/v3/gw?method=item.search&appKey=myKey&format=json&kw="
							+ searchkey + "&pageNo=1&pageSize=20&channelId="
							+ videotype + "&inDays=7&media=v&sort=s");
			URLConnection conn = url.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line = "";
			while ((line = reader.readLine()) != null)
			{
				readOneLineBuff.append(line);
			}
			content = readOneLineBuff.toString();
			reader.close();
		}
		catch (MalformedURLException e)
		{
			logger.error("----MalformedURLException----", e);
		}
		catch (IOException e2)
		{
			logger.error("----IOException----", e2);
		}
		return "@" + content;
	}
}
